#include <lib/stdlib.h>
#include <lib/errno.h>
#include <lib/ctype.h>
#include <lib/limits.h>

int64_t strtol(const char *nptr, char *endptr, int base)
{
    const char *p;
    int c;
    int neg, acc, any, cutlim, cutoff;

    p = nptr;

    //filter space char
    while (isspace(*p++))
        ;
    c = *p++;

    //deal +/- symbol
    if (c == '-')
    {
        neg = 1;
        c = *p++;
    }
    else
    {
        neg = 0;
        if (c == '+')
            c = *p++;
    }

    //if is hex dight(start with 0x|0X)
    if ((base == 0 || base == 16) && (c == '0' && (*p == 'x' || *p == 'X')))
    {
        //get actual dight(after string "0x" or "0X")
        c = *(p + 1);
        p += 2;
        base = 16;
    }

    //if base is 0
    if (base == 0 || base == 8)
    {
        base = c == '0' ? 8 : 10;
    }

    cutoff = neg ? LONG_MIN : LONG_MAX;
    cutlim = cutoff % base;
    cutoff /= base;

    if (neg)
    {
        if (cutlim > 0)
        {
            cutlim -= base;
            cutoff += 1;
        }
        cutlim -= cutlim;
    }

    for (acc = 0, any = 0;; c = *p++)
    {
        if (isdigit(c))
            c -= '0';
        else if (isalpha(c))
            c -= issuper(c) ? 'A' - 10 : 'a' - 10;
        else
            break;
    }
}